<script setup>
import { onMounted, ref, reactive, computed } from "vue";
import { useAuthStore } from "@/store/auth";
import {
  getUserList,
  createUser,
  updateUser,
  deleteUser,
  getRoleList,
  updateUserRoles,
  getAllPermissions,
  updateRolePermissions,
} from "@/api/auth";
import { ElMessage } from "element-plus";

const loading = ref(false);
const submitting = ref(false);
const dialogVisible = ref(false);
const dialogType = ref("add");
const roleList = ref([]);
const userFormRef = ref(null);
const options = ref(null);
const authStore = useAuthStore();

// 用户表单
const userForm = reactive({
  id: "",
  name: "",
  permissions: "",
});

// 表单验证规则
const userFormRules = computed(() => ({
  name: [
    { required: true, message: "请输入角色名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  permissions: [{ required: false }],
}));

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const response = await getRoleList();
    roleList.value = response;
    console.log(response);
  } catch (error) {
    console.error("获取角色列表失败:", error);
    ElMessage.error("获取角色列表失败");
  }
};

const fetchPermissions = async () => {
  {
    try {
      const response = await getAllPermissions();
      console.log(response);
      options.value = response.map((permission) => ({
        value: permission.id,
        label: permission.name,
      }));
    } catch (err) {
      console.error("");
      ElMessage.error("");
    }
  }
};

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});

function handleEdit(data) {
  dialogVisible.value = true;

  console.log(data);

  let permission_ids = data.permissions.map((item) => item.id);
  console.log(permission_ids);
  userForm["id"] = data.id;
  userForm.name = data.name;
  userForm.permissions = permission_ids;
  // 编辑角色信息
}

const submitForm = async () => {
  if (!userFormRef.value) return;

  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        let role_id = userForm.id;
        delete userForm.id; // 移除id属性
        const formData = {
          name: userForm.name,
          permissions: userForm.permissions.map((id) => ({ id })),
        };
        const response = await updateRolePermissions(role_id, formData);

        await authStore.loadPermissions();

        fetchRoleList();

        console.log(response);
        ElMessage.success("修改成功");
        dialogVisible.value = false;
      } catch (error) {
        console.error("操作失败:", error);
        ElMessage.error(error.response?.data?.message || "操作失败");
      } finally {
        submitting.value = false;
      }
    }
  });
};

onMounted(() => {
  fetchRoleList();
  fetchPermissions();
});
</script>

<template>
  <div class="user-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>权限分配</h3>
        </div>
      </template>

      <!-- 表格区域 -->
      <div class="table-section">
        <el-table
          v-loading="loading"
          :data="roleList"
          style="width: 100%"
          border
          stripe
          highlight-current-row
        >
          <el-table-column prop="name" label="角色名" width="200" />
          <el-table-column prop="permissions" label="当前权限" width="300">
            <template #default="scope">
              <div
                class="permission-in-role"
                v-for="item in scope.row['permissions']"
                :key="item.id"
              >
                <div class="item-permission-name">{{ item.name }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="handleEdit(scope.row)"
                >修改权限</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            background
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="80px"
      >
        <el-form-item label="角色名" prop="username">
          <el-input v-model="userForm.name" placeholder="请输入角色名" />
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-select
            v-model="userForm.permissions"
            placeholder="请选择权限"
            multiple
            style="width: 440px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            确定
          </el-button>
          <!-- <el-button @click="console.log(userForm)">123</el-button> -->
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<style scoped>
.user-management {
  padding: 20px;
  height: 100%;
  min-height: calc(100vh - 120px);
  box-sizing: border-box;
  background-color: #f5f7fa;
}

.box-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
  border-bottom: 1px solid #ebeef5;
}

.search-form {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
}

.table-section {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 16px;
}

:deep(.el-table) {
  flex: 1;
  min-height: 0;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
  min-height: 200px;
  max-height: calc(100vh - 400px);
}

:deep(.el-table .cell) {
  padding: 8px;
}

:deep(.el-table--striped .el-table__row--striped td) {
  background-color: #fafafa;
}

.pagination-section {
  position: relative;
  z-index: 1;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: auto;
}

:deep(.el-pagination) {
  padding: 0;
  margin: 0;
  justify-content: flex-end;
  white-space: nowrap;
}

:deep(.el-card__body) {
  height: 100%;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 0;
}

.role-tag {
  margin-right: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 响应式布局 */
@media screen and (max-width: 1200px) {
  .search-form {
    .el-form-item {
      margin-right: 16px;
    }
  }
}

@media screen and (max-width: 768px) {
  .search-form {
    .el-form-item {
      width: 100%;
      margin-right: 0;
    }
  }
}
</style>
